// 名字列表页
let api = require("../../utils/api.js")
Page({
  data: {
    loading: true,
    name: '',
    nameList: []
  },
  onLoad: function(options) {
    this.setData({
      name: options.name
    })
    this.loadPage();
  },

  //搜索用户昵称
  loadPage: function(cb) {
    let self = this;
    this.setData({
      loading: false
    })
    api.http("steam/searchName", "POST", {
      name: encodeURI(self.data.name),
    }).then((res) => {
      console.log(res.data)
      let status = res.data.code;
      if (status == 1) {
        self.setData({
          nameList: res.data.datas
        });
        this.setData({
          loading: true
        });
      } else {
        this.setData({
          loading: true
        });
        wx.showModal({
          title: '提示',
          showCancel: false,
          content: res.data.message,
        });
      }
    })
  },

  //绑定操作
  bind: function(value) {
    let self = this;
    let token = wx.getStorageSync('token');
    if (value) {
      this.setData({
        loading: false
      })

      api.http("pubg/bind", "POST", {
        'token': token,
        'steamId': value,
      }).then((res) => {
        let status = res.data.code;
        if (status == 1) {
          self.setData({
            loading: true,
          });
          wx.showToast({
            title: "绑定成功",
            duration: 1000
          });
          wx.redirectTo({ url: '../index/index' });
        } else {
          self.setData({
            loading: true,
          });
          wx.showModal({
            title: '提示',
            showCancel: false,
            content: res.data.message,
          })
        }
      })
    }
  },
  // 分享
  onShareAppMessage: function() {
    return {
      title: '绝地求生群排行',
      path: 'pages/index/index'
    }
  },
  //搜索列表点击处理
  tap: function(e) {
    let self = this;
    let userInfo = this.data.nameList[e.target.dataset.idx];
    let id = userInfo.id;
    let name = userInfo.nickName;
    let profiles = userInfo.profiles;
    wx.showModal({
      title: '提示',
      content: '是否绑定 ' + name + '?',
      success: function(res) {
        if (res.confirm) {
          if (profiles) {
            self.bind(profiles);
          } else {
            self.setData({
              loading: false
            })
            api.http('steam/getSteamProfileBySteamId', 'POST', {
              steamId: id
            }).then((res) => {
              if (res.data.code == 1) {
                let steamId = res.data.datas
                self.bind(steamId)
              } else {
                wx.showModal({
                  title: '提示',
                  showCancel: false,
                  content: '获取信息失败，请重试！',
                })
                self.setData({
                  loading: true
                })
              }
            })
          }
        }
      }
    })
  }
})